//
//  HLStartQusetionViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/12.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLStartQusetionViewController.h"
#import "WRNavigationBar.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import "HLLoginTextFiled.h"
#import "HLPlaceHolderTextView.h"
#import "MBProgressHUD+HL.h"
#import "HttpRequestManager.h"
#import "HLUserInfo.h"

@interface HLStartQusetionViewController ()<UITextViewDelegate>

/** 发布按钮  */
@property (nonatomic ,strong) UIButton *publishButton;
/** 标题  */
@property (nonatomic ,strong) HLLoginTextFiled *titleTextFiled;
/** 问题  */
@property (nonatomic ,strong) HLPlaceHolderTextView *contentTextView;

@end

@implementation HLStartQusetionViewController

- (UIButton *)publishButton
{
    if (!_publishButton) {
        _publishButton = [[UIButton alloc] init];
        _publishButton.enabled = NO;
        [_publishButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
        [_publishButton setTitleColor:kColorMineBlueBG forState:UIControlStateNormal];
        NSString *title = self.type == HLReplyTypeQusetion ? @"发起":@"回复";
        [_publishButton setTitle:title forState:UIControlStateNormal];
        [_publishButton addTarget:self action:@selector(publishButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_publishButton sizeToFit];
    }
    return _publishButton;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
    [UIColor wr_setDefaultNavBarBarTintColor:[UIColor whiteColor]];
    [UIColor wr_setDefaultNavBarTitleColor:HLRGB(30, 30, 30)];
    [UIColor wr_setDefaultNavBarTintColor:HLRGB(30, 30, 30)];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSForegroundColorAttributeName:HLRGB(30, 30, 30)}];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIColor wr_setDefaultNavBarBarTintColor:kColorNavBG];
    [UIColor wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    [UIColor wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNavItem];
    
    [self setUI];
    
    if(self.type == HLReplyTypeQusetion){
        RAC(_publishButton,enabled) = [RACSignal combineLatest:@[_titleTextFiled.rac_textSignal,_contentTextView.rac_textSignal] reduce:^id _Nullable(NSString *title,NSString *content){
            return @(title.length > 0  && content.length > 0 );
        }];

    }else{
        RAC(_publishButton,enabled) = [RACSignal combineLatest:@[_contentTextView.rac_textSignal] reduce:^id _Nullable(NSString *content){
            return @( content.length > 0 );
        }];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return  UIStatusBarStyleDefault;
}

- (void)setNavItem
{
    self.navigationItem.title = self.type == HLReplyTypeQusetion ? @"发起一个新的问题" : @"回复评论";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.publishButton];
    self.view.backgroundColor = HLRGB(245,245, 245);
}

- (void)setUI
{
    self.titleTextFiled = [[HLLoginTextFiled alloc]init];
    self.titleTextFiled.placeholder = @"输入标题(最多20个字)";
    self.titleTextFiled.frame = CGRectMake(10, 74, ScreenWidth - 20, 40);
    self.titleTextFiled.backgroundColor = [UIColor whiteColor];
    self.titleTextFiled.layer.borderColor = HLRGB(230, 230, 230).CGColor;
    [self.view addSubview:self.titleTextFiled];
    self.titleTextFiled.hidden = self.type == HLReplyTypeComment;
    

    
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(10,self.type == HLReplyTypeComment ? 74: ( CGRectGetMaxY(self.titleTextFiled.frame) + 10), ScreenWidth-20, 0.3* ScreenWidth  -  10)];
    contentView.layer.borderColor = HLRGB(230, 230, 230).CGColor;
    contentView.layer.borderWidth = 1.0f;
    contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:contentView];
    
    self.contentTextView = [[HLPlaceHolderTextView alloc] initWithFrame:CGRectMake(10, 0, ScreenWidth-40, 0.3* ScreenWidth  -  10)];
    self.contentTextView.font = [UIFont systemFontOfSize:15];
    self.contentTextView.backgroundColor = [UIColor whiteColor];
    self.contentTextView.placeholder =  self.type == HLReplyTypeQusetion ?@"输入问题" : @"输入回复";
    self.contentTextView.placeholderColor = HLRGB(200, 200, 200);
    [contentView addSubview:self.contentTextView];
}


- (void)publishButtonClick
{
    if (self.type == HLReplyTypeQusetion) {
        [self questionRequest];
    }else{
        [self replyRequest];
    }
}

- (void)questionRequest
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestNewQues signStr];
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"title"] = [self switchStringEncode:self.titleTextFiled.text];
    params[@"content"] = [self switchStringEncode:self.contentTextView.text];
    params[@"course_id"] = self.question_course_id;
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestNewQues parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            [MBProgressHUD showSuccessMessage:@"创建成功"];
            [weakSelf leftItemClick];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:kHLUserAskQuestionSuccessNotifacation object:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}

- (void)replyRequest
{
    [MBProgressHUD show];
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestAnswerQues signStr];
    params[@"title_id"] = self.comment_title_id ;
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"content"] = [self switchStringEncode:self.contentTextView.text];
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestAnswerQues parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        
        if ([responseObject[@"code"] integerValue] == 200) {
            [MBProgressHUD showSuccessMessage:@"回复成功"];
            [weakSelf leftItemClick];
            if(self.commentCompletionBlock){
                self.commentCompletionBlock();
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}


- (NSString *)switchStringEncode:(NSString *)str
{
    return str;
    /**** 表情字符 适配  转换发送到服务器,请求下来再转换回来 ****/
//    return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
}

- (void)leftItemClick
{
    [self.contentTextView resignFirstResponder];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}




@end
